/**
 * PerformanceMonitor - 性能监控工具
 * 追踪FPS、内存使用、渲染时间等性能指标
 */

class PerformanceMonitor {
  constructor() {
    this.fps = 60
    this.frameCount = 0
    this.lastTime = 0
    this.renderTimes = []
    this.maxRenderTimesSamples = 60
    this.listeners = new Map()
    
    // 性能阈值
    this.thresholds = {
      lowFPS: 30,
      criticalFPS: 15,
      highRenderTime: 16.67 // 60fps = 16.67ms per frame
    }
  }

  /**
   * 更新性能指标
   */
  update(timestamp) {
    this.frameCount++
    
    // 每秒计算一次FPS
    if (timestamp - this.lastTime >= 1000) {
      this.fps = this.frameCount
      this.frameCount = 0
      this.lastTime = timestamp
      
      // 检测性能问题
      this.checkPerformance()
      
      // 触发更新事件
      this.emit('fps-update', { fps: this.fps })
    }
  }

  /**
   * 记录渲染时间
   */
  recordRenderTime(time) {
    this.renderTimes.push(time)
    
    // 保持样本数量在限制内
    if (this.renderTimes.length > this.maxRenderTimesSamples) {
      this.renderTimes.shift()
    }
  }

  /**
   * 获取平均渲染时间
   */
  getAverageRenderTime() {
    if (this.renderTimes.length === 0) return 0
    
    const sum = this.renderTimes.reduce((a, b) => a + b, 0)
    return sum / this.renderTimes.length
  }

  /**
   * 检测性能问题
   */
  checkPerformance() {
    const avgRenderTime = this.getAverageRenderTime()
    
    // FPS过低
    if (this.fps < this.thresholds.criticalFPS) {
      console.warn('Critical FPS detected:', this.fps)
      this.emit('critical-performance', { 
        fps: this.fps, 
        avgRenderTime,
        level: 'critical'
      })
    } else if (this.fps < this.thresholds.lowFPS) {
      console.warn('Low FPS detected:', this.fps)
      this.emit('low-performance', { 
        fps: this.fps, 
        avgRenderTime,
        level: 'low'
      })
    }
    
    // 渲染时间过长
    if (avgRenderTime > this.thresholds.highRenderTime) {
      console.warn('High render time detected:', avgRenderTime.toFixed(2), 'ms')
      this.emit('high-render-time', { 
        avgRenderTime,
        fps: this.fps
      })
    }
  }

  /**
   * 获取性能指标
   */
  getMetrics() {
    return {
      fps: this.fps,
      avgRenderTime: this.getAverageRenderTime(),
      timestamp: Date.now()
    }
  }

  /**
   * 重置统计
   */
  reset() {
    this.fps = 60
    this.frameCount = 0
    this.lastTime = 0
    this.renderTimes = []
  }

  /**
   * 事件监听
   */
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event).push(callback)
  }

  /**
   * 移除事件监听
   */
  off(event, callback) {
    if (this.listeners.has(event)) {
      const listeners = this.listeners.get(event)
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }

  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('Performance monitor callback error:', error)
        }
      })
    }
  }

  /**
   * 获取性能建议
   */
  getRecommendations() {
    const metrics = this.getMetrics()
    const recommendations = []
    
    if (metrics.fps < this.thresholds.criticalFPS) {
      recommendations.push({
        level: 'critical',
        message: '帧率严重过低，建议降低渲染质量或减少动画效果'
      })
    } else if (metrics.fps < this.thresholds.lowFPS) {
      recommendations.push({
        level: 'warning',
        message: '帧率偏低，建议优化渲染逻辑'
      })
    }
    
    if (metrics.avgRenderTime > this.thresholds.highRenderTime * 2) {
      recommendations.push({
        level: 'critical',
        message: '渲染时间过长，建议简化绘制逻辑'
      })
    } else if (metrics.avgRenderTime > this.thresholds.highRenderTime) {
      recommendations.push({
        level: 'warning',
        message: '渲染时间偏高，可能影响流畅度'
      })
    }
    
    return recommendations
  }
}

export default PerformanceMonitor
